﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Mailer.Model;
using System.Timers;
using Mailer.Utilities;
using System.Threading; 

namespace Mailer
{
	// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
	// visit http://go.microsoft.com/?LinkId=9394801

	public class MvcApplication : System.Web.HttpApplication
	{
		public static void RegisterRoutes(RouteCollection routes)
		{
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

			routes.MapRoute("PublicList", "public/l/{id}/{action}/{dummy}", new { controller = "PublicList", action = "", id = "", dummy = "" }, new { dummy = ".*", action = "[a-z]+" });
			routes.MapRoute("PublicApp", "public/a/{id}/{action}/{dummy}", new { controller = "PublicApp", action = "", id = "", dummy = "" }, new { dummy = ".*", action = "[a-z]+" });
			routes.MapRoute("PublicMail", "public/m/{id}/{action}/{dummy}", new { controller = "PublicMail", action = "", id = "", recipient = Guid.Empty, dummy = "" }, new { dummy = ".*", action = "[a-z.]+" });
			routes.MapRoute("PublicMail2", "public/m/{id}/{recipient}/{action}/{dummy}", new { controller = "PublicMail", action = "", id = "", recipient = Guid.Empty, dummy = "" }, new { dummy = ".*", action = "[a-z.]+" });
			
			routes.MapRoute("APIs", "api/{action}", new { controller = "API", action = "" });

			routes.MapRoute("App", "applications/{id}/{action}", new { controller = "Application", action = "Index", id = "" }, new { id = "[0-9a-f-]+" } );
			routes.MapRoute("App2", "applications/{action}", new { controller = "Application", action = "Index" });

			routes.MapRoute("Default", "{controller}/{id}/{action}", new { controller = "Home", action = "Index", id = "" }, new { id = "[0-9a-f-]*" });
			routes.MapRoute("Default2", "{controller}/{action}", new { controller = "Home", action = "Index" });

		}

		protected void Application_Start()
		{
			Configuration.Initialize();
			
			log4net.Config.XmlConfigurator.Configure();
			log4net.LogManager.GetLogger("").Debug("In Application_Start.");

			BeginRequest += new EventHandler(MvcApplication_BeginRequest);
			EndRequest += new EventHandler(MvcApplication_EndRequest);
			
			RegisterRoutes(RouteTable.Routes);

			SessionUtilities.Init();


			Logger.Debug(typeof(MvcApplication), "Starting " + Configuration.SendThreads+" send-threads with interval: " + Configuration.SendTimerInterval);
			if (Configuration.SendTimerInterval > 0)
			{
				int sendinterval = Configuration.SendTimerInterval * 1000;
				int threadintervaloffset = sendinterval / Configuration.SendThreads;

				for (int k = 0; k < Configuration.SendThreads; k++)
				{
					System.Timers.Timer t = new System.Timers.Timer();
					t.Interval = sendinterval;
					t.Elapsed += new ElapsedEventHandler(t_Elapsed);
					t.Start();

					Thread.Sleep(threadintervaloffset);
				}
			}

			Logger.Debug(typeof(MvcApplication),"Starting poll-timer with interval: " + Configuration.PollTimerInterval);
			if (Configuration.PollTimerInterval > 0)
			{
				System.Timers.Timer t2 = new System.Timers.Timer();
				t2.Interval = Configuration.PollTimerInterval * 1000;
				t2.Elapsed += new ElapsedEventHandler(t2_Elapsed);
				t2.Start();
			}
		}

		void t_Elapsed(object sender, ElapsedEventArgs e)
		{
			log4net.LogManager.GetLogger("").Debug("In t_Elapsed.");
			SessionUtilities.BeginRequest();
			Mailer.Controllers.APIController ac = new Mailer.Controllers.APIController();
			ActionResult ar = ac.ProcessQueue();
			SessionUtilities.EndRequest();
			if (ac.LastProcessItemCount > 0)
			{
				// väck upp timern
				((System.Timers.Timer)sender).Interval = Configuration.SendTimerInterval * 1000;
			}
			else
			{
				// sätt timern till sleepläge, 5 ggr segare
				((System.Timers.Timer)sender).Interval = Configuration.SendTimerInterval * 5000;
			}
		}
		
		void t2_Elapsed(object sender, ElapsedEventArgs e)
		{
			log4net.LogManager.GetLogger("").Debug("In t2_Elapsed.");
			SessionUtilities.BeginRequest();
			Mailer.Controllers.APIController ac = new Mailer.Controllers.APIController();
			ActionResult ar = ac.PollMails();
			SessionUtilities.EndRequest();
		}

		void MvcApplication_EndRequest(object sender, EventArgs e)
		{
		//	log4net.LogManager.GetLogger("").Debug("In MvcApplication_EndRequest.");
			//	SessionUtilities.CloseSession();
			SessionUtilities.EndRequest();
		}

		void MvcApplication_BeginRequest(object sender, EventArgs e)
		{
		//	log4net.LogManager.GetLogger("").Debug("In MvcApplication_BeginRequest.");
		//	SessionUtilities.OpenSession();
			SessionUtilities.BeginRequest();
		}
	}
}